package com.zrrd.gmall.rabbit.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/*
* 消息发送确认
* ConfirmCallback:只确认消息到达了交换机
* ReturnCallback:消息到了交换机 没有到队列触发*/

@Slf4j
@Component
public class MQProductAckConfig implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //修饰一个非静态的方法 该方法只会被服务器执行一次在构造方法之后执行
    @PostConstruct
    public void init(){
        //指定ConfirmCallback
        rabbitTemplate.setConfirmCallback(this);
        //指定ReturnCallback
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack){
            log.info("消息发送成功===>" + JSON.toJSONString(correlationData));
        } else {
            log.info("消息发送失败===>原因：" + cause + "===>数据" + JSON.toJSONString(correlationData));
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        //反向序列化对象输出消息信息
        System.out.println("消息主体：" + new String(message.getBody()));
        System.out.println("应答码：" + replyCode);
        System.out.println("描述：" + replyText);
        System.out.println("对应交换机：" + exchange);
        System.out.println("对应路由器的键：" + routingKey);
    }
}
